<?php

namespace App\Controllers;

use App\Models\NewsModel;
use CodeIgniter\Exceptions\PageNotFoundException;

class News extends BaseController
{

    public function new()
    {
        helper('form');

        return view('templates/header', ['title' => 'Create a news item'])
            . view('news/create')
            . view('templates/footer');
    }
    public function index()
{
    $model = model(NewsModel::class);

    $data = [
        'news'  => $model->getNews(),
        'title' => 'Zhang Junrong News Archive', // 将"您的名字"替换为您的实际名字
    ];

    return view('templates/header', $data)
        . view('news/index')
        . view('templates/footer');
}
    public function view($slug = null)
    {
        $model = model(NewsModel::class);

        $data['news'] = $model->getNews($slug);

        if (empty($data['news'])) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Cannot find the news item: ' . $slug);
        }

        $data['title'] = $data['news']->title;

        return view('templates/header', $data)
            . view('news/view')
            . view('templates/footer');
    }

    public function create()
    {
        helper('form');

        $data = $this->request->getPost(['title', 'body']);

        // Checks whether the submitted data passed the validation rules.
        if (! $this->validateData($data, [
            'title' => 'required|max_length[255]|min_length[3]',
            'body'  => 'required|max_length[5000]|min_length[10]',
        ])) {
            // The validation fails, so returns the form.
            return $this->new();
        }

        // Gets the validated data.
        $post = $this->validator->getValidated();

        $model = model(NewsModel::class);

        $model->save([
            'title' => $post['title'],
            'slug'  => url_title($post['title'], '-', true),
            'body'  => $post['body'],
        ]);

        return view('templates/header', ['title' => 'Create a news item'])
            . view('news/success')
            . view('templates/footer');
    }
    public function delete(int $id = null): string
    {
        $model = model(NewsModel::class);
   
        // 检查新闻是否存在
        $news = $model->find($id);
        if (empty($news)) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Cannot find the news item with id: '. $id);
        }
   
        // 删除新闻
        $model->delete($id);
   
        $data = [
            'title' => 'News Deleted',
            'news_title' => $news->title // 改为对象属性访问方式
        ];
       
        return view('templates/header', $data)
            . view('news/deleted')
            . view('templates/footer');
    }
}